var form = layui.form, table = layui.table, layer = layui.layer, $ = layui.jquery, deleteSplitIds = [], id = getQueryVariable("id");

$('#editor-form').find('input,textarea,select').attr('disabled',true);
//表单初始值，修改时调用
if (id != "") {
    form.val("editor-form", {
        "receiptnumber": "进入查看",
    })
}

//收款明细数据
let detailList = [];
//拆分明细数据
let splitList = [];
//退款明细数据
let refundList = [];
//附件明细数据
let annexList = [];
//操作日志数据
let operationLog = [];

layer.ready(function () {
    //获取详情信息
    $.ajax({
        url:"receivePayment/getAllDetail?id="+id,
        success:function(res){
            if(res.status == 200){
                //主表信息赋值
                if(null != res.data){
                    //主表数据
                    let vo =  res.data;
                    form.val("editor-form", {
                        "billNo" : vo.billNo,
                        "time" : vo.time,
                        "customerName" : vo.customerName,
                        "accountName" : vo.accountName,
                        "currency" : vo.currency,
                        "rmbRate" : vo.rmbRate,
                        "usdRate" : vo.usdRate,
                        "entryAmount" : vo.entryAmount,
                        "bankDeductionExcept" : vo.bankDeductionExcept,
                        "bankDeductionCapital" : vo.bankDeductionCapital,
                        "collectionAmount" : vo.collectionAmount,
                        "claimed" : vo.claimed,
                        "toBeClaimed" : vo.toBeClaimed,
                        "salesman" : vo.salesman,
                        "voucherCompanyName" : vo.voucherCompanyName,
                        "operator" : vo.operator,
                        "memo" : vo.memo
                    });

                    //收款明细数据
                    if(null != res.data.detailList && res.data.detailList.length > 0){
                        detailList = res.data.detailList;
                        table.reload('claimdetailtableid',{data : detailList});
                    }

                    //拆分明细数据
                    if(null != res.data.splitList && res.data.splitList.length > 0){
                        splitList = res.data.splitList;
                        table.reload('breakdetailtableid',{data : splitList});
                    }

                    //退款明细数据
                    if(null != res.data.refundList && res.data.refundList.length > 0){
                        refundList = res.data.refundList;
                        table.reload('refunddetailtableid',{data : refundList});
                    }

                    //附件明细数据
                    if(null != res.data.annexList && res.data.annexList.length > 0){
                        annexList = res.data.annexList;
                        table.reload('attachmenttableid',{data : annexList});
                    }

                    //日志
                    if(!isEmpty(res.data.logList) && res.data.logList.length > 0){
                        operationLog = res.data.logList;
                        table.reload('logtableid',{data:operationLog});
                    }
                }
                return false;
            }else {
                layer.msg(res.msg, {icon: 5});
            }
        }
    });
    form.render();

});


//---认领明细
table.render({
    elem: '#claimdetail',
    id: 'claimdetailtableid',
    data: detailList,
    cols: [[
        {field: 'invoiceNumber', width: 120, title: '发票编号',sort:true},
        {field: 'contractNo', width: 120, title: '合同编号',sort:true},
        {field: 'typeName', width: 120, title: '收款类型',sort:true},
        {field: 'collectionAmount', width: 120, title: '收汇金额',sort:true},
        {field: 'foreignBankDeductions', width: 120, title: '国外银行扣费',sort:true},
        {field: 'domesticBankCharge', width: 120, title: '国内银行扣费',sort:true},
        {field: 'amountClaimed', width: 120, title: '认领金额',sort:true},
        {field: 'allocatedAmount', width: 120, title: '已分摊金额',sort:true},
        {field: 'unallocatedAmount', width: 120, title: '未分摊金额',sort:true},
        {field: 'totalContract', width: 120, title: '合同总额',sort:true},
        {field: 'totalInvoice', width: 120, title: '发票总额',sort:true},
        {field: 'claimDate', width: 120, title: '认领日期', sort:true},
        {field: 'claimCustomer', width: 120, title: '认领客户', sort:true},
        {field: 'claimSalesman', width: 120, title: '认领业务员', sort:true},
        {field: 'memo', width: 120, title: '备注', sort:true}
    ]],
    page: true,
    height: 380
});

//---拆分明细
table.render({
    elem: '#breakdetail',
    id: 'breakdetailtableid',
    data: splitList,
    toolbar: '#claimdetailtoolbar',
    cols: [[
        {checkbox: true},
        {field: 'invoiceNumber',  title: '发票编号',sort:true},
        {field: 'contractNo',  title: '合同编号',sort:true},
        {field: 'splitAmount',  title: '拆分金额',sort:true},
        {field: 'amountClaimed', title:'认领金额',sort:true,width: 120},
        {field: 'unallocatedAmount', title:'未分摊金额',sort:true,width: 120},
        {field: 'foreignBankDeductions',  title: '国外银行扣费',sort:true},
        {field: 'domesticBankCharge',  title: '国内银行扣费',sort:true},
        {field: 'totalContract',  title: '合同总额',sort:true},
        {field: 'claimCustomer',  title: '认领客户', sort:true},
        {field: 'claimSalesman',  title: '认领业务员', sort:true},
        {field: 'memo',  title: '备注', sort:true}
    ]],
    page: true,
    height: 380
});

table.on('toolbar(breakdetailtable)', function (obj) {
    let checkStatus = table.checkStatus(obj.config.id);
    switch (obj.event) {
        case 'del':
            let data = checkStatus.data, delList = [];
            data.forEach(function (n, i) {
                delList.push(n.id);
            });
            if (delList != '') {
                layer.confirm('确认删除？',confirmInfo(3,6), function (index) {
                    let cbList = table.cache["breakdetailtableid"];
                    for (var i = 0; i < cbList.length; i++) {
                        delList.forEach((item, index) => {
                            //当数组中任意一个元素的rowIndex值与取消复选框的元素对象属性rowIndex的下标值相等，则在数组中删除该元素
                            if (typeof (cbList[i]) != "undefined" && item == cbList[i].id) {
                                deleteSplitIds.push(cbList[i].id);
                                cbList.splice(i, 1);
                            }
                        })
                    }
                    table.reload("breakdetailtableid", {
                        data: cbList,
                    });
                    layer.msg('删除成功');
                })
            } else {
                layer.msg('请选择需要删除的行');
            }
            break;
    }
});

//监听提交
form.on('submit(form-element)', function (data) {
    let datas = JSON.stringify(deleteSplitIds);
    $.ajax({
        type:"POST",
        dataType:"json",
        contentType: 'application/json',
        data:datas,
        url:"receivePayment/deleteSplit",
        success:function(res){
            if(res.status == 200){
                layer.msg("保存成功", {icon: 6});
                setTimeout(function () {
                    //保存成功则刷新提交过来的界面 并关闭此页面
                    parent.detab("views/jsp/Money/collection.jsp");
                    parent.intab("views/jsp/Money/collection.jsp", "收款")
                    parent.detab("views/jsp/Money/tpl/viewcollection.jsp" + (id == '' ? '' : '?id=' + id));
                }, 1000);
            }else {
                layer.msg(res.msg, {icon: 5});
            }
            return false;
        }
    });
});

//---退款明细
table.render({
    elem: '#refunddetail',
    id: 'refunddetailtableid',
    data: refundList,
    cols: [[
        {field: 'invoiceNumber',  title: '发票编号',sort:true},
        {field: 'contractNo',  title: '合同编号',sort:true},
        {field: 'refundAmount', title: '退款金额', sort:true},
        {field: 'foreignBankDeductions',  title: '国外银行扣费',sort:true},
        {field: 'domesticBankCharge',  title: '国内银行扣费',sort:true},
        {field: 'totalContract',  title: '合同总额',sort:true},
        {field: 'totalInvoice',  title: '发票总额',sort:true},
        {field: 'claimCustomer',  title: '认领客户', sort:true},
        {field: 'claimSalesman',  title: '认领业务员', sort:true},
        {field: 'memo',  title: '备注', sort:true}
    ]],
    page: true,
    height: 380
});

//---附件
table.render({
    elem: '#attachment'
    , data: annexList
    , toolbar: '#attachmenttoolbar'
    , cols: [[
        {field: 'fileName', event:'fileName', title: '文件名', fixed: true}
        , {field: 'uploadTime', title: '上传日期', fixed: true}
        , {fixed: 'right', width: 180, align: 'center', toolbar: '#attachmenteditor', title: '操作'}
    ]]
    , id: 'attachmenttableid'
    , height: 380
    , page: true
});

table.on('tool(attachmenttable)', function (obj) {
    let data = obj.data;
    if (obj.event === 'download') { //下载
        let xmlHttpRequest = new XMLHttpRequest();
        let url = "wjinfo/downloadfile2?filename=" + data.filePath;
        xmlHttpRequest.open('GET', url, true);
        //设置请求头
        xmlHttpRequest.setRequestHeader("Content-type", "application/json")
        xmlHttpRequest.responseType = "blob";
        xmlHttpRequest.send(null);

        xmlHttpRequest.onload = function() {
            let content = xmlHttpRequest.response;
            // 组装a标签
            let elink = document.createElement("a");

            //设置文件下载路径
            elink.download = decodeURIComponent(data.fileName);
            elink.style.display = "none";
            let blob = new Blob([content], { type: 'application/force-download' });

            //解决下载不存在文件的问题，根据blob大小判断
            if(blob.size==0){
                layer.msg('服务器没找到此文件，请联系管理员!');
            }else{
                elink.href = window.URL.createObjectURL(blob);
                document.body.appendChild(elink);
                elink.click();
                document.body.removeChild(elink);
            }

        }
    }else if (obj.event === 'fileName'){
        onLineFile(data.filePath);
    }
});

//---操作日志
    table.render({
        elem: '#otherwarehouselog'
        , data: operationLog
        , cols: [[
              {field: 'operationType', title: '操作类型', fixed: true}
            , {field: 'operationName', title: '操作员'}
            , {field: 'operationTime', title: '操作日期'}
            , {field: 'operationContent', title: '修改内容'}
        ]]
        , id: 'logtableid'
        , height: 380
        , limit: 30//显示的数量
        , page: true
    });

//提示信息渲染
function confirmInfo(icon, anim) {
    let data = {
        icon: icon,
        title: "提示",
        offset: "auto",
        skin: 'layui-layer-molv',
        anim: anim
    }
    return data;
}

//字段是否为空或者零
function isEmpty(obj){
    if(typeof obj == "undefined" || obj == null || obj == "" || obj == 0){
        return true;
    }else{
        return false;
    }
}